package com.bjtu.literatureclient.shiro;

import com.bjtu.literatureclient.domain.user.User;
import com.bjtu.literatureclient.service.team.ITeamService;
import com.bjtu.literatureclient.service.user.IUserService;
import com.bjtu.literatureclient.util.ValidatorUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {

	private static final Logger logger = LoggerFactory.getLogger(UserRealm.class);

	public static final String SESSIOIN_USER_KEY = "userInfo";

	public static String[] roleList = new String[]{"superAdmin", "selfAdmin", "teamAdmin", "superUser", "highUser", "middleUser", "primaryUser"};
	public static String[] roleNameList = new String[]{"系统管理员", "独立管理员", "团队管理员", "超级用户", "高级用户", "中级用户", "初级用户"};

	@Autowired
	private IUserService userService;
	@Autowired
	private ITeamService teamService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		long start = System.currentTimeMillis();
		logger.info("授权...");
		User user = (User) principalCollection.getPrimaryPrincipal();
		logger.info("当前用户是： " + user.getUserName());
		String role = user.getUserRole();
        Set<String> roles = new HashSet<>();

        int roleIndex = 6;
        try {
            roleIndex = Integer.parseInt(role);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        // 用户-角色
        roles.add(roleList[roleIndex]);
        // 用户-权限
		List<String> permissions = new ArrayList<>();
		
		// 根据角色分配权限（目前实行一对一）
		permissions.add(roleList[roleIndex]);
		
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(roles);
		simpleAuthorizationInfo.addStringPermissions(permissions);
		long end = System.currentTimeMillis();
		logger.info("程序运行时间："+(end-start)+"ms");
		return simpleAuthorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		logger.info("认证...");

		// shiro判断逻辑
		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
		
		User fakeUser = new User();
		String username = token.getUsername();
		
		fakeUser.setUserName(username);
		fakeUser.setPassword(String.copyValueOf(token.getPassword()));
		
		User user = null;
		
		if (ValidatorUtils.isEmail(username)) {
			//如果是邮箱登录
			fakeUser.setUserEmail(username);
			user = this.userService.loginByEmail(fakeUser);
		} else {
			//如果是账号登录
			fakeUser.setUserNo(username);
			user = this.userService.login(fakeUser);
		}
		
		// 未找到该用户名
		if (user == null) {
			throw new UnknownAccountException("用户不存在！");
		} 
		
		if (!user.getUserRole().equals("0") && teamService.checkTeamState(user.getUserTeamNo()) == 0) {
			throw new LockedAccountException();
		}
		
		if (user.getUserState().equals("1") || user.getUserState().equals("2")) {
			if (user.getUserState().equals("1")) {
				boolean result = userService.setUserState(user.getUserNo(), "2");
				logger.info("用户号："+user.getUserNo()+" 为第一次登录，执行状态修改程序...（修改结果："+(result?"成功 ）":"失败 ）"));
			}
			Session session = SecurityUtils.getSubject().getSession();
			session.setAttribute(UserRealm.SESSIOIN_USER_KEY, user);
			return new SimpleAuthenticationInfo(user, user.getPassword(), null, getName());

		} else {
			logger.error("该用户未注册或已被删除！");
			throw new IncorrectCredentialsException("该用户未注册或已被删除！");
		}
	}

}
